/*
 * video.c
 *
 * ============================================================================
 * Copyright (c) Texas Instruments Inc 2009
 *
 * Use of this software is controlled by the terms and conditions found in the
 * license agreement under which this software has been supplied or provided.
 * ============================================================================
 */

#include <stdio.h>
#include <string.h>

//#include <xdc/std.h>

//#include <ti/sdo/ce/Engine.h>
//#include <ti/sdo/ce/osal/Memory.h>

//#include <ti/sdo/dmai/Fifo.h>
//#include <ti/sdo/dmai/Pause.h>
//#include <ti/sdo/dmai/BufTab.h>
//#include <ti/sdo/dmai/VideoStd.h>
#include <ti/sdo/dmai/BufferGfx.h>
//#include <ti/sdo/dmai/Rendezvous.h>
#include <ti/sdo/dmai/ce/Vdec.h>
#include <ti/sdo/dmai/ce/Venc.h>
#include <ti/sdo/dmai/ce/Ienc1.h>
#include <ti/xdais/dm/trimps_plate.h>
#include <sendBuff.h>

#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <termios.h>

#include "video.h"
#include "demo.h"
//#include "jpg.h"
#include <time.h>
#include "sendBuff.h"

#include "seft_struct.h"
#include "seft_util.h"
#include "ftp.h"
#include "rabbitmq.h"
#include "sw_perform.h"

#define CAPTURE_PIPE_SIZE       2
#define DISPLAY_PIPE_SIZE       2
#define NUM_VIDEO_BUFS          CAPTURE_PIPE_SIZE + DISPLAY_PIPE_SIZE

/* The masks to use for knowing when a buffer is free */
#define CODEC_FREE              0x1
#define DISPLAY_FREE            0x2
#define SOCKET			int
#define INVALID_SOCKET		-1
#define SUCCESS             	0
#define FAILURE             	-1
//#define SERVIP	    "202.127.26.182"
//#define SERVIP	    "202.127.26.182"
#define SERVIP	    "192.168.1.77"
#define SERVPORT 		80					//·�˿؍
#define MAXBACKLOG		5					//خ´􁬽Ԋ�/////////////////////////

FILE *info_lhs;   //add by LHS

VIDENC_InArgs inArgs;
VIDENC_OutArgs outArgs;
char *remote_adress = NULL;
unsigned int remote_port = 0;
#define BMP_ALIGN (4)
#define WIDTH			720
#define HEIGHT			576
#define OMIT_DISPLAY    (0)
volatile sig_atomic_t flag = 0;
void input_handler(int num) {
	flag = 1;
	printf("interrupt dectected,flag = %d\n", flag);

}

Ienc1_Handle Ienc1_control(Ienc1_Handle hIe, IMGENC1_DynamicParams *dynParams)
{
  IMGENC1_Handle       hEncode;
  IMGENC1_Status       encStatus;
  XDAS_Int32           status;
  
  hEncode = Ienc1_getVisaHandle(hIe);
  /* Set dynamic parameters */
  encStatus.data.buf = NULL;
  encStatus.size = sizeof(IMGENC1_Status);
  status = IMGENC1_control(hEncode, XDM_SETPARAMS, dynParams, &encStatus);
  if (status != IMGENC1_EOK) {
    printf("XDM_SETPARAMS failed, status=%d\n", status);
    IMGENC1_delete(hEncode);
    free(hIe);
    return NULL;
    }
    return hIe;
}

/******************************************************************************
 * encodedecode
 ******************************************************************************/
static Int encodedecode(Venc_Handle hVe, Vdec_Handle hVd, Buffer_Handle hVidBuf,
		Buffer_Handle hEncBuf, Buffer_Handle hOutBuf, Fifo_Handle displayFifo) {
	/* Make sure the whole buffer is used for input and output */
	BufferGfx_resetDimensions(hVidBuf);

    //printf("encodedecode-hEncBuf size is %d\n",Buffer_getSize(hEncBuf));
    //printf("encodedecode-hVidBuf size is %d\n",Buffer_getSize(hVidBuf));
    //printf("encodedecode-hOutBuf size is %d\n",Buffer_getSize(hOutBuf));
    //printf("enter encodedecode.\n");
    //printf("venc inbufsize %d, outbufsize %d.\n",Venc_getInBufSize(hVe),Venc_getOutBufSize(hVe));
	//memcpy(Buffer_getUserPtr(hEncBuf), Buffer_getUserPtr(hVidBuf), Venc_getInBufSize(hVe));
	//Buffer_setNumBytesUsed(hEncBuf,Venc_getInBufSize(hVe));
    if (Venc_process(hVe, hVidBuf, hEncBuf) < 0) 
    {
		ERR("Failed to encode video buffer\n");
		return FAILURE;
	}
/////////////////////////////////////////////
//    printf("the flag is :%d \n",outArgs.result.flag);
//  	printf("the color is :%d \n",outArgs.result.color);
  	//printf("x=%d,y=%d,w=%d,y=%d\n",outArgs.plateInfo.rect.x,outArgs.plateInfo.rect.y,outArgs.plateInfo.rect.width,outArgs.plateInfo.rect.height);
	//printf("the number is: %s \n", outArgs.plateInfo.number);
// 	printf("the info is :%s \n",outArgs.result.info);
/////////////////////////////////////////////

	if (Buffer_getNumBytesUsed(hEncBuf) == 0) {
		ERR("Encoder created 0 sized output frame\n");
		return FAILURE;
	}

	/* Update global data for user interface */
	gblIncVideoBytesProcessed(Buffer_getNumBytesUsed(hEncBuf));

	//Copy the encoded buffer to out buffer
	memcpy(Buffer_getUserPtr(hOutBuf), Buffer_getUserPtr(hEncBuf), Venc_getInBufSize(hVe));
	Buffer_setNumBytesUsed(hOutBuf,Venc_getInBufSize(hVe));
#if OMIT_DISPLAY
	if (Fifo_put(displayFifo, hOutBuf) < 0) {
		ERR("Failed to send buffer to display thread\n");
		return FAILURE;
	}
#endif
    //usleep(1000*800);
    printf("exit encodedecode\n");
	return SUCCESS;
}


int serial_init(int fd)
{
	struct termios oldoptions;
	struct termios options = {0};

	//if(tcgetattr(fd, &options) != 0)   
	if(tcgetattr(fd, &oldoptions) != 0)   
	{ 
		printf("getting options failed!\n");   
		return -1;
	}
	
	
	tcflush(fd, TCIOFLUSH);
	//cfsetispeed(&options, B115200);
	//cfsetospeed(&options, B115200);
	cfsetispeed(&options, B9600);
	cfsetospeed(&options, B9600);
	options.c_cflag |= (CLOCAL | CREAD);
	
	options.c_cflag &= ~PARENB;
	options.c_cflag &= ~CSTOPB;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;
  options.c_cc[VMIN] = 1;
	//options.c_iflag |= IGNPAR;
	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	options.c_oflag &= ~OPOST;
	
	
	if(tcsetattr(fd, TCSANOW, &options) != 0)   
	{ 
		printf("setting options failed!\n");   
		return -1;
	}	
	
	return 0;
}

/******************************************************************************
 * videoThrFxn
 ******************************************************************************/
Void *videoThrFxn(Void *arg) {
	VideoEnv *envp = (VideoEnv *) arg;
	Void *status = THREAD_SUCCESS;
	VIDDEC_Params defaultDecParams = Vdec_Params_DEFAULT;
	VIDDEC_DynamicParams defaultDecDynParams = Vdec_DynamicParams_DEFAULT;
	VIDENC_Params defaultEncParams = Venc_Params_DEFAULT;
	VIDENC_DynamicParams defaultEncDynParams = Venc_DynamicParams_DEFAULT;
	BufferGfx_Attrs gfxAttrs = BufferGfx_Attrs_DEFAULT;
	BufferGfx_Attrs outAttrs = BufferGfx_Attrs_DEFAULT;
	Buffer_Attrs bAttrs = Buffer_Attrs_DEFAULT;
	Vdec_Handle hVd = NULL;
	Venc_Handle hVe = NULL;
	BufTab_Handle hBufTab = NULL;
	Engine_Handle hEngine = NULL;
	Buffer_Handle hEncBuf = NULL;
	Buffer_Handle hOutBuf = NULL;
	Int ret = Dmai_EOK;
	Int numBufs = 0;
	Buffer_Handle hVidBuf, hDstBuf;
	VIDDEC_Params *decParams;
	VIDDEC_DynamicParams *decDynParams;
	VIDENC_Params *encParams;
	VIDENC_DynamicParams *encDynParams;
	Int32 bufSize;
	Int fifoRet;
	Int bufIdx;
	int widthStep;
	int plen;
	int i;
    IMGENC1_Params params = Ienc1_Params_DEFAULT;
	IMGENC1_DynamicParams dynParams = Ienc1_DynamicParams_DEFAULT;
	BufferGfx_Attrs jpgGfxAttrs = BufferGfx_Attrs_DEFAULT;
	Buffer_Attrs jpgBAttrs = Buffer_Attrs_DEFAULT;
	Ienc1_Handle hIe = NULL;
	Engine_Handle hEncEngine = NULL;
    Server_Handle hServer;
    Server_MemStat memStat;
    int numMemSegs;
	Buffer_Handle hJpgOutBuf = NULL;
	Buffer_Handle hJpgInBuf = NULL;
    const char outJpgDir[] = "trimpsOut";
	//	FILE *out = NULL;
   	char *dirName = envp->dirName;
  	//printf("dirName = %s.\n",dirName);
    	remote_adress = envp->remote_adress;
    	remote_port = envp->remote_port;
	//char *		    BGR;
	//char *		    pBMP;
	/* Use supplied params if any, otherwise use defaults */
	decParams = envp->decParams ? envp->decParams : &defaultDecParams;
	decDynParams =
			envp->decDynParams ? envp->decDynParams : &defaultDecDynParams;

	encParams = envp->encParams ? envp->encParams : &defaultEncParams;
	encDynParams =
			envp->encDynParams ? envp->encDynParams : &defaultEncDynParams;

	gblSetImageWidth(envp->imageWidth);
	gblSetImageHeight(envp->imageHeight);

	gfxAttrs.colorSpace = ColorSpace_UYVY;
	gfxAttrs.dim.width = envp->imageWidth;
	gfxAttrs.dim.height = envp->imageHeight;
	gfxAttrs.dim.lineLength = BufferGfx_calcLineLength(gfxAttrs.dim.width,
			gfxAttrs.colorSpace);

	outAttrs.colorSpace = ColorSpace_UYVY;
	outAttrs.dim.width = envp->imageWidth;
	outAttrs.dim.height = envp->imageHeight;
	outAttrs.dim.lineLength = BufferGfx_calcLineLength(outAttrs.dim.width,
			outAttrs.colorSpace);
	outAttrs.bAttrs.useMask = DISPLAY_FREE;

	int fd = open("/dev/dm644x_button", 0);
	if (fd < 0) {

		perror("open device /dev/dm644x_button failed!\n");
		exit(1);

	}
	int oflags;
	signal(SIGIO, input_handler);
	fcntl(fd, F_SETOWN, getpid());
	oflags = fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, oflags | FASYNC);
	
	int fds;/* File descriptor for the port */

  /*fds = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
  if (fds == -1)
  {
      fputs("open_port: Unable to open /dev/ttyS0 -\n", stderr);
      return -1;
  }
  
  if(serial_init(fds))
  {
  		fputs("initializing serial port failed\n", stderr);
      return -1;
  }
*/

	if (envp->passThrough) {
		bufSize = gfxAttrs.dim.lineLength * gfxAttrs.dim.height;

		/* Only the display thread can own a buffer since no codecs are used */
		gfxAttrs.bAttrs.useMask = DISPLAY_FREE;
	} else {
		/* Open the codec engine */
		printf("Engine_open\n");
		hEngine = Engine_open(envp->engineName, NULL, NULL);

		if (hEngine == NULL) {
			ERR("Failed to open codec engine %s\n", envp->engineName);
			cleanup (THREAD_FAILURE);
		} else
			printf("Successed to open codec engine %s\n", envp->engineName);
        hServer = Engine_getServer(hEngine);
        Server_getNumMemSegs(hServer,&numMemSegs);

		/* Set the resolution to match the specified resolution */
		encParams->maxWidth = envp->imageWidth;
		encParams->maxHeight = envp->imageHeight;
		encParams->inputChromaFormat = XDM_YUV_422ILE;

		//Jpeg encoder param
		params.maxWidth = envp->imageWidth;
		params.maxHeight = envp->imageHeight;
		params.forceChromaFormat = XDM_YUV_422P;

		dynParams.inputWidth = params.maxWidth;
		dynParams.inputHeight = params.maxHeight;
		dynParams.captureWidth = params.maxWidth;
		dynParams.qValue = 90;
		dynParams.inputChromaFormat = XDM_YUV_422ILE;

		//if ((out = fopen("test.jpg", "wb")) == NULL) {
		//	printf("can't write to file %s\n", "test.jpg");
		//	cleanup (THREAD_FAILURE);
		//}
        /***********************************************
         * create dir for saving image
         * *********************************************/
        if(access(outJpgDir,F_OK) != 0)
        {
            int ret = mkdir(outJpgDir,S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
            if(ret != 0)
            {
                printf("create trimpsOut dir failed.\n");
            }
        }
		hIe = Ienc1_create(hEngine, "jpegenc", &params, &dynParams);
		if (hIe == NULL) {
			ERR("Failed to create jpeg encoder: %s\n", "jpegenc");
			cleanup (THREAD_FAILURE);
		} else
			printf("jpeg encoder created.\n");

		/* Set up codec parameters depending on bit rate */
		if (envp->videoBitRate < 0) {
			/* Variable bit rate */
			encParams->rateControlPreset = IVIDEO_NONE;

			/*
			 * If variable bit rate use a bogus bit rate value (> 0)
			 * since it will be ignored.
			 */
			encParams->maxBitRate = 2000000;
		} else {
			/* Constant bit rate */
			encParams->rateControlPreset = IVIDEO_LOW_DELAY;
			encParams->maxBitRate = envp->videoBitRate;
		}

		encDynParams->targetBitRate = encParams->maxBitRate;
		encDynParams->inputWidth = encParams->maxWidth;
		encDynParams->inputHeight = encParams->maxHeight;

		/* Create the video encoder */
		hVe = Venc_create(hEngine, envp->videoEncoder, encParams, encDynParams);
		if (hVe == NULL) {
			ERR("Failed to create video encoder: %s\n", envp->videoEncoder);
			cleanup (THREAD_FAILURE);
		}

		decParams->maxWidth = encParams->maxWidth;
		decParams->maxHeight = encParams->maxHeight;
		decParams->forceChromaFormat = XDM_YUV_422ILE;

		/* Which output buffer size does the codec require? */
		bufSize = Venc_getInBufSize(hVe);

		/* Allocate buffer for encoded data */
		hEncBuf = Buffer_create(bufSize, &bAttrs);
        printf("hEncBuf size is %d\n",Buffer_getSize(hEncBuf));
		/* Allocate buffer for encoded data */
		hOutBuf = Buffer_create(bufSize, BufferGfx_getBufferAttrs(&outAttrs));
        printf("hOutBuf size is %d\n",Buffer_getSize(hOutBuf));
		if (hEncBuf == NULL) {
			ERR("Failed to allocate buffer for encoded data\n");
			cleanup (THREAD_FAILURE);
		}

		/* Which output buffer size does the codec require? */
		Int32 JpgBufSize = Ienc1_getInBufSize(hIe);

		printf("inBufSize of jpeg is %d\n", JpgBufSize);

		/* Allocate buffer for encoded data */
		hJpgInBuf = Buffer_create(JpgBufSize,
				BufferGfx_getBufferAttrs(&jpgGfxAttrs));

		JpgBufSize = Ienc1_getOutBufSize(hIe);

		printf("outBufSize of jpeg is %d\n", JpgBufSize);

		/* Allocate buffer for encoded data */
		hJpgOutBuf = Buffer_create(JpgBufSize, &jpgBAttrs);

		if (hJpgInBuf == NULL) {
			ERR("Failed to allocate buffer for jpeg encoded data\n");
			cleanup (THREAD_FAILURE);
		}
        printf("hJpgInBuf size is %d\n",Buffer_getSize(hJpgInBuf));
		/* A buffer can be owned by either the codec or the display thread */
		gfxAttrs.bAttrs.useMask = CODEC_FREE | DISPLAY_FREE;
	}

	/* Allocate video buffers */
	hBufTab = BufTab_create(NUM_VIDEO_BUFS, bufSize,
			BufferGfx_getBufferAttrs(&gfxAttrs));

	if (hBufTab == NULL) {
		ERR("Failed to create BufTab for display pipe\n");
		cleanup (THREAD_FAILURE);
	}

	/* Prime the capture pipe with buffers */
	for (bufIdx = 0; bufIdx < NUM_VIDEO_BUFS; bufIdx++) {
		hDstBuf = BufTab_getFreeBuf(hBufTab);

		if (hDstBuf == NULL) {
			ERR("Failed to get free buffer from BufTab\n");
			BufTab_print(hBufTab);
			cleanup (THREAD_FAILURE);
		}

		if (Fifo_put(envp->hCaptureInFifo, hDstBuf) < 0) {
			ERR("Failed to send buffer to display thread\n");
			cleanup (THREAD_FAILURE);
		}
	}

	/* Make sure the display thread is stopped when it's unlocked */
	Pause_on(envp->hPausePrime);

	/* Signal that initialization is done and wait for other threads */
	Rendezvous_meet(envp->hRendezvousInit);


	/* Process one buffer to figure out buffer requirements */
	fifoRet = Fifo_get(envp->hCaptureOutFifo, &hVidBuf);

	if (fifoRet < 0) {
		ERR("Failed to get buffer from video thread\n");
		cleanup (THREAD_FAILURE);
	}

	/* Did the capture thread flush the fifo? */
	if (fifoRet == Dmai_EFLUSH) {
		cleanup (THREAD_SUCCESS);
	}



	/* Prime the display thread */
	for (bufIdx = 0; bufIdx < numBufs - CAPTURE_PIPE_SIZE - 1; bufIdx++) {
		if (ret != Dmai_EFIRSTFIELD) {
			/* Get a video buffer from the capture thread */
			fifoRet = Fifo_get(envp->hCaptureOutFifo, &hVidBuf);

			if (fifoRet < 0) {
				ERR("Failed to get buffer from video thread\n");
				cleanup (THREAD_FAILURE);
			}

			/* Did the capture thread flush the fifo? */
			if (fifoRet == Dmai_EFLUSH) {
				cleanup (THREAD_SUCCESS);
			}
		}

	
		}

		/* Release the display thread, it is now fully primed */
		Pause_off(envp->hPausePrime);

		//printf("Enter video main loop\n");
		/* Main loop */
		while (!gblGetQuit()) {
            //printf("###########################main loop################################\n");
			/* Get a buffer from the capture thread */
			fifoRet = Fifo_get(envp->hCaptureOutFifo, &hVidBuf);

			if (fifoRet < 0) {
				ERR("Failed to get buffer from capture thread\n");
				cleanup (THREAD_FAILURE);
			}

            //printf("enter mainloop1111111111\n");
			/* Did the capture thread flush the fifo? */
			if (fifoRet == Dmai_EFLUSH) {
				cleanup (THREAD_SUCCESS);
			}
			
			int n,j;
			char buf[100];
            const int SpeedBuffSize = 4;
			if (flag) {
			//if (1) {
				/*
				 * Encode and decode the buffer from the capture thread and
				 * send any display buffers to the display thread.
				 */
                //printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@flag = 1@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
				flag = 0;
                time_t time_now;
                struct tm *tm_local;
                static time_t s_time;
                char saveJpgFileName[60];
                //printf("start to read uart\n");				
                //n = read(fds, buf, sizeof(buf)); 
				//tcflush(fds, TCIFLUSH);
				
				//if(n <  SpeedBuffSize || buf[0] != 0xFF)
				//{ 
				//		continue;
				//}
                /*********************************************
                 *create image path
                 * ********************************************/
                strcpy(saveJpgFileName,outJpgDir);
                strcat(saveJpgFileName,"/");
                time_now = time((time_t *)0);
                if(time_now != s_time)//avoid the same image name in one second-use rand()
                {
                    srand((unsigned int)time_now);
                    s_time = time_now;
                }
                tm_local = localtime(&time_now);
                strftime(saveJpgFileName + strlen(saveJpgFileName),sizeof(saveJpgFileName) - strlen(saveJpgFileName) - 1,"%Y-%m-%d-%H-%M-%S",tm_local);
				//Jpg Encode
				printf("YUV size is %d\n", Buffer_getNumBytesUsed(hVidBuf));

				if (Buffer_getSize(hJpgInBuf) < Buffer_getNumBytesUsed(hVidBuf)) {
					printf("YUV size is not match\n");
					cleanup (THREAD_FAILURE);
				}

				memcpy(Buffer_getUserPtr(hJpgInBuf), Buffer_getUserPtr(hVidBuf),
						Buffer_getNumBytesUsed(hVidBuf));
                Buffer_setNumBytesUsed(hJpgInBuf, Buffer_getNumBytesUsed(hVidBuf));
                
                //Buffer_setNumBytesUsed(hJpgOutBuf,0);
	            if(Ienc1_control(hIe, &dynParams) == NULL)
                {
                     printf("Failed to control the encode\n");
                     cleanup(THREAD_FAILURE);
                }

			
                if (Ienc1_process(hIe, hJpgInBuf, hJpgOutBuf) < 0) {
					printf("Failed to encode image buffer\n");
					cleanup (THREAD_FAILURE);
				}

				printf("JPEG encoded: %d bytes\n",
						(int) Buffer_getNumBytesUsed(hJpgOutBuf));
				//Main algorithm
                //cleanup(THREAD_FAILURE);//end of one frame;
                for(i = 0; i < numMemSegs; i++)
                {
                    Server_getMemStat(hServer,i,&memStat);
                    printf("%s: base: 0x%x size: 0x%x used: 0x%x max free block: 0x%x\n\n", memStat.name, memStat.base, memStat.size, memStat.used,memStat.maxBlockLen);
                }
	            printf("encodedecode 3\n");
				ret = encodedecode(hVe, hVd, hVidBuf, hEncBuf, hOutBuf, envp->hDisplayInFifo);
				if (ret < 0) {
					cleanup (THREAD_FAILURE);
				}
                //save jpg image
                int randValue = rand() % 1000;
                sprintf(saveJpgFileName + strlen(saveJpgFileName),"-%03d-",randValue);
                if(outArgs.plateInfo.flag == 1)
                {
                    switch(outArgs.plateInfo.color){
                        case 0:
                           strcat(saveJpgFileName,"蓝牌-");
                        break;

                        case 1:
                            strcat(saveJpgFileName,"黄牌-");
                        break;

                        case 2:
                            strcat(saveJpgFileName,"黑牌-");
                        break;

                        case 3:
                            strcat(saveJpgFileName,"白牌-");
                        break;
                        default:
                            strcat(saveJpgFileName,"未知-");
                        break;
                    }
                    strcat(saveJpgFileName,outArgs.plateInfo.number);
                }
                else
                {
                    strcat(saveJpgFileName,"unkown");
                }
                strcat(saveJpgFileName,".jpg");
				printf("%s\n",saveJpgFileName);
                FILE *pJpgFile = fopen(saveJpgFileName,"w+");
                if(pJpgFile == NULL)
                {
                    printf("create JpgOut.jpg failed.\n");
                    cleanup(THREAD_FAILURE);
                }
                int writeLen = fwrite(Buffer_getUserPtr(hJpgOutBuf),1,Buffer_getNumBytesUsed(hJpgOutBuf),pJpgFile);
                if(writeLen != Buffer_getNumBytesUsed(hJpgOutBuf))
                {
                    printf("write JpgOut.jpg failed.\n");
                    cleanup(THREAD_FAILURE);
                }
                fclose(pJpgFile);
                /*****************************************************************
                 *ftp transport
                 * **************************************************************/
                seft_plate_encode_t input_node;
		        p_seft_plate_encode_t p_input_node=&input_node;	

            //inital the input parameters by LHS.
		        memset(p_input_node,0,sizeof(seft_plate_encode_t));

		//set the flag of the image by LHS.
		        p_input_node->plate_upload_pend = seft_image_exist;
		        p_input_node->scene_upload_pend = seft_image_not_exist;

            //get the time info by LHS
		        p_input_node->time=time_now;              //input parameter[time ]
                
		//set the speed of the target
		        (p_input_node->msg).speed = 20 + rand()%60;//input parameter[speed]...............

		//
		        (p_input_node->msg).plateNumberColor = outArgs.plateInfo.color;//input parameter[color]

		        strcpy((p_input_node->msg).terminalID,"SD04");//input parameter[terminalID:SD01 or HD01]

		        strcpy((p_input_node->msg).panoramaName,"2");

               //set the vehiclePicName 
                const char *picName=(const char*)(strrchr(saveJpgFileName,'/')+1);
 		        strcpy((p_input_node->msg).vehiclePicName,picName);

               //set the eventID
		        char eventID[250];
		        sprintf(eventID,"e_%s",picName);
		        strcpy((p_input_node->msg).eventID,eventID);

               //set shortedTime
                char shortedTime[35];
		        struct tm ptime;
                localtime_r(&(p_input_node->time),&ptime);
		        sprintf(shortedTime,"%d-%d-%dT%d:%d:%d.2600000+08.00",ptime.tm_year+1900,ptime.tm_mon+1,ptime.tm_mday,ptime.tm_hour,ptime.tm_min,ptime.tm_sec);
		        strcpy((p_input_node->msg).shortedTime,shortedTime);
           //set relativePath
	     	    char relativePath[30];

		        sprintf(relativePath,"%s/%d/%02d/%02d/%02d/%02d/",(p_input_node->msg).terminalID,ptime.tm_year+1900,ptime.tm_mon+1,ptime.tm_mday,ptime.tm_hour,ptime.tm_min);

		        strcpy((p_input_node->msg).relativePath,relativePath);

		        //printf("(p_input_node->msg).terminalID============================>%s\n",(p_input_node->msg).terminalID);
		        strcpy((p_input_node->msg).plateNumber,outArgs.plateInfo.number);//input parameter[plateNumber]
	            //strcpy((p_input_node->msg.plateNumber),"沪A12345");//delet when capture from the camera.
                //p_input_node->msg.plateNumberColor=0;
                //printf("*************************************** %s\n",dirfile);
	
		        strcpy(p_input_node->plate_pathname,saveJpgFileName);
		        //printf("************************************************enter my program\n");
#if 1
				info_lhs=fopen("info_lhs.txt","ab+");//add by LHS
#endif


#if 0
                struct timeval first,second;
		        float timeuse;
		        gettimeofday(&first,NULL);

#endif
		        seft_sem_writer_perform(&input_node);
				
#if 1
				fclose(info_lhs);//add by LHS
#endif
#if 0
		        gettimeofday(&second,NULL);
		        timeuse=(second.tv_sec-first.tv_sec)*1000000+second.tv_usec-first.tv_usec;
		        timeuse/=1000000;
		        printf("==============================%f==========================\n",timeuse);

#endif

                flag = 0;
			} else {
				/* Send the buffer through to the display thread unmodified */
#if OMIT_DISPLAY
				if (Fifo_put(envp->hDisplayInFifo, hVidBuf) < 0) {
					ERR("Failed to send buffer to display thread\n");
					cleanup (THREAD_FAILURE);
				}
#endif
            }

			/* Get a buffer from the display thread to send to the capture thread */
			if (Fifo_put(envp->hCaptureInFifo, hVidBuf) < 0) {
				ERR("Failed to send buffer to capture thread\n");
				cleanup (THREAD_FAILURE);
			}
		}

		cleanup:
		/* Make sure the other threads aren't waiting for us */
		Rendezvous_force(envp->hRendezvousInit);
		Pause_off(envp->hPauseProcess);
		Pause_off(envp->hPausePrime);
#if OMIT_DISPLAY
        Fifo_flush(envp->hDisplayInFifo);
#endif
		/* Meet up with other threads before cleaning up */
		Rendezvous_meet(envp->hRendezvousCleanup);

		/* Clean up the thread before exiting */
		if (hEncBuf) {
			Buffer_delete(hEncBuf);
		}

		if (hVd) {
			Vdec_delete(hVd);
		}

		if (hVe) {
			Venc_delete(hVe);
		}

		if (hEngine) {
			Engine_close(hEngine);
		}

		if (hBufTab) {
			BufTab_delete(hBufTab);
		}
        return status;
	}

